import React from "react";
import { Address, Cell } from "@nutui/nutui-react";
import { useState, useEffect } from "react";
import axios from "axios";
import { Popup, Button } from "antd-mobile";
import { Radio } from "antd-mobile";
import "./Cart.css";
import { useLocation } from "react-router-dom";

export default function Dingdan() {
  const [visible1, setVisible1] = useState(false);
  const location = useLocation();
  const [text, setText] = useState("请选择地址");
  const [visible, setVisible] = useState(false);
  const [products, setProducts] = useState([]);
  const [deliveryMethod, setDeliveryMethod] = useState(false);
  
  const addressList = [
    {
      id: 1,
      addressDetail: "",
      cityName: "次渠镇",
      countyName: "通州区",
      provinceName: "北京市",
      selectedAddress: true,
      townName: "",
      name: "探探鱼1",
      phone: "182****1718",
    },
    {
      id: 2,
      addressDetail: "",
      cityName: "钓鱼岛全区",
      countyName: "",
      provinceName: "钓鱼岛",
      selectedAddress: false,
      townName: "",
      name: "探探鱼2",
      phone: "182****1718",
    },
    {
      id: 3,
      addressDetail: "京东大厦",
      cityName: "大兴区",
      countyName: "科创十一街18号院",
      provinceName: "北京市",
      selectedAddress: false,
      townName: "",
      name: "探探鱼3",
      phone: "182****1718",
    },
  ];

  const handleAddressSelect = (data) => {
    const { provinceName, cityName, countyName, townName, addressDetail } = data;
    if (provinceName) {
      setText(`${provinceName}${cityName}${countyName}${townName}${addressDetail}`);
    }
  };

  useEffect(() => {
    const fetchProducts = async () => {
      try {
        const productIds = location.search.split("=")[2].split(",");
        const response = await axios.get(
          `http://localhost:3000/zlp/pro?pros=${productIds}`
        );
        setProducts(response.data.info);
      } catch (error) {
        console.error("获取商品信息失败:", error);
      }
    };
    
    fetchProducts();
  }, [location.search]);

  const handlePayment = async () => {
    if (text === "请选择地址") {
      alert("请先选择收货地址");
      return;
    }

    try {
      const basePrice = parseInt(location.search.split("=")[1].split("&")[0]);
      const totalPrice = deliveryMethod ? basePrice + 5 : basePrice;
      
      const paymentResponse = await axios.post("http://localhost:3000/zlp/pay", {
        name: text,
        orderId: Math.random().toString(36).substr(2, 9),
        price: totalPrice,
      });

      // 更新购物车状态
      await axios.post("http://localhost:3000/zlp/cahngecart", {
        cartid: location.search.split("=")[2].split(","),
      });

      // 跳转到支付页面
      window.location.href = paymentResponse.data.paymentUrl;
    } catch (error) {
      console.error("支付处理失败:", error);
      alert("支付处理失败，请重试");
    }
  };

  const basePrice = parseInt(location.search.split("=")[1].split("&")[0]);
  const totalPrice = deliveryMethod ? basePrice + 5 : basePrice;

  return (
    <div className="order-container">
      {/* 地址选择 */}
      <div className="address-section">
        <Cell
          title="选择地址"
          description={text}
          onClick={() => setVisible(true)}
          className="address-cell"
        />
        <Address
          visible={visible}
          type="exist"
          existList={addressList}
          onExistSelect={handleAddressSelect}
          title="选择地址"
          onClose={() => setVisible(false)}
        />
      </div>

      {/* 商品展示 */}
      <div className="products-section">
        <h3 className="section-title">商品清单</h3>
        <div className="products-grid">
          {products.map((item, index) => (
            <img
              key={index}
              src={item.img[0].url}
              alt="商品图片"
              className="product-image"
            />
          ))}
        </div>
        
        <Cell
          className="delivery-cell"
          onClick={() => setVisible1(true)}
        >
          <span>配送方式</span>
          <span>{deliveryMethod ? "配送到寝" : "自提"}</span>
        </Cell>
      </div>

      {/* 配送方式弹窗 */}
      <Popup
        visible={visible1}
        onMaskClick={() => setVisible1(false)}
        position="bottom"
        bodyStyle={{ height: "40vh", padding: "20px" }}
      >
        <h3 className="popup-title">配送方式</h3>
        <Radio.Group
          value={deliveryMethod}
          onChange={setDeliveryMethod}
        >
            <Radio value={false} block className="delivery-option">
              自提
              <div className="option-description">到店自取，无需配送费</div>
            </Radio>
            <Radio value={true} block className="delivery-option">
              快递到寝
              <div className="option-description">
                <span className="delivery-fee">+5元配送费</span>
                <span className="delivery-time">预计30分钟内送达</span>
              </div>
            </Radio>
        </Radio.Group>
      </Popup>

      {/* 底部支付栏 */}
      <div className="payment-bar">
        <div className="price-section">
          <span className="total-text">合计：</span>
          <span className="price">￥{totalPrice.toFixed(2)}</span>
          {deliveryMethod && <span className="fee-note">(含5元配送费)</span>}
        </div>
        <Button
          color="primary"
          size="large"
          className="pay-button"
          onClick={handlePayment}
        >
          去支付
        </Button>
      </div>
    </div>
  );
}